#!/bin/bash

set -e  # 如果任何命令失败，脚本将立即退出

# 定义 Redis 配置文件路径
REDIS_CONFIG_FILE="/etc/redis/redis.conf"

# 1. 安装 Redis
install_redis() {
    echo "Installing Redis..."
    # 更新系统包信息并安装 Redis
    sudo apt-get update
    sudo apt-get install -y redis-server
    echo "Redis installed successfully."
}

# 2. 修改 Redis 配置
modify_redis_config() {
    echo "Modifying Redis configuration..."

    # 确保 Redis 配置文件存在
    if [ ! -f "$REDIS_CONFIG_FILE" ]; then
        echo "Redis configuration file not found at $REDIS_CONFIG_FILE"
        exit 1
    fi

    # 备份配置文件
    sudo cp $REDIS_CONFIG_FILE $REDIS_CONFIG_FILE.bak
    echo "Backup of redis.conf created at $REDIS_CONFIG_FILE.bak"

    # 修改 bind 行，允许监听所有接口
    sudo sed -i -E 's/^#?bind .*/bind 0.0.0.0 ::1/' $REDIS_CONFIG_FILE

    # 关闭保护模式，允许远程连接
    sudo sed -i 's/^protected-mode.*/protected-mode no/' $REDIS_CONFIG_FILE

    # 设置 Redis 监听的端口，修改为 9998
    sudo sed -i 's/^port.*/port 9998/' $REDIS_CONFIG_FILE

    # 设置密码为 leex123454，如果行已存在则替换，否则追加新行
    if grep -q "^requirepass" $REDIS_CONFIG_FILE; then
        sudo sed -i 's/^requirepass.*/requirepass leex123454/' $REDIS_CONFIG_FILE
    else
        echo "requirepass leex123454" | sudo tee -a $REDIS_CONFIG_FILE
    fi

    echo "Redis configuration modified successfully."
}

# 3. 重启 Redis 服务
restart_redis() {
    echo "Restarting Redis service..."
    sudo systemctl restart redis-server
    echo "Redis service restarted."
}

# 4. 验证 Redis 安装和配置
verify_redis() {
    echo "Verifying Redis installation and configuration..."

    # 检查 Redis 是否正在运行
    if systemctl is-active --quiet redis-server; then
        echo "Redis server is running."
    else
        echo "Redis server is not running. Please check the logs."
    fi

    # 使用密码连接 Redis 验证配置
    redis-cli -p 9998 -a leex123454 ping
    if [ $? -eq 0 ]; then
        echo "Redis is accessible with the configured password."
    else
        echo "Failed to connect to Redis with the configured password."
    fi
}

# 主流程
main() {
    echo "Starting Redis installation and configuration..."
    install_redis
    modify_redis_config
    restart_redis
    verify_redis
    echo "Redis installation and configuration completed!"
}

main
